package com.springboot.demo.controller;

import com.springboot.demo.controller.viewobject.UserVO;
import com.springboot.demo.error.BusinessException;
import com.springboot.demo.error.EmBusinessError;
import com.springboot.demo.response.CommonReturnType;
import com.springboot.demo.service.UserService;
import com.springboot.demo.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;

//这里的controller是指作为控制类注入到ioc的key
@Controller("user")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/get")
    @ResponseBody
    public CommonReturnType getUser(@RequestParam(name="id") Integer id) throws BusinessException {
        //调service
        UserModel userModel=userService.getUserById(id);

        //若获取的对应用户信息不存在,直接抛到tomcat容器层 =》直接500页面
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }

        UserVO userVO = convertFromModel(userModel);
        return CommonReturnType.create(userVO);
    }

    /**
     * 将核心领域模型对象转成ui用的对象
     * @param userModel
     * @return
     */
    private UserVO convertFromModel(UserModel userModel){
        UserVO uv = new UserVO();
        if(userModel == null){
            return null;
        }else{
            BeanUtils.copyProperties(userModel,uv);
            return uv;
        }
    }

    //定义exceptionhandle 解决未被controller层吸收的exception,即自定义拦截的异常方法
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Object handlerExceptin(HttpServletRequest request,Exception ex){
        CommonReturnType commonReturnType = new CommonReturnType();
        commonReturnType.setStatus("fail");
        commonReturnType.setData(ex);
        return commonReturnType;
    }

}
